#include "skillsproxymodel.h"
#include "skill.h"


#include <dtwentymodel.h>


SkillsProxyModel::SkillsProxyModel(QObject *parent) :
    QSortFilterProxyModel(parent)
{
}

QVariant SkillsProxyModel::data(const QModelIndex &index, int role) const
{
    if (role != Qt::CheckStateRole)
    {
        return QSortFilterProxyModel::data(index, role);
    }

    if (m_classSkills.isNull())
    {
        return QVariant();
    }


    foreach (Skill* skill, m_classSkills->findChildren<Skill*>(QString(), Qt::FindDirectChildrenOnly))
    {
        if (skill->name() == index.data().toString())
        {
            return Qt::Checked;
        }
    }

    return Qt::Unchecked;

}

bool SkillsProxyModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (role != Qt::CheckStateRole)
    {
        return QSortFilterProxyModel::setData(index, value, role);
    }
    if (m_classSkills.isNull())
    {
        return false;
    }

    foreach (Skill* skill, m_classSkills->findChildren<Skill*>(QString(), Qt::FindDirectChildrenOnly))
    {
        // class skill exists
        if (skill->name() == index.data().toString())
        {
            if (value.toInt() == Qt::Checked)
            {
                return false;
            }

            skill->setParent(0);
            skill->deleteLater();

            emit dataChanged(index, index);
            return true;
        }
    }

    if (value.toInt() == Qt::Unchecked)
    {
        return false;
    }

    Skill* skill = qobject_cast<Skill*>(m_classSkills->newChild());
    skill->setReferencePath(index.data(DTwentyModel::Role_PATH).toString());

    emit dataChanged(index, index);
    return true;

}


Qt::ItemFlags SkillsProxyModel::flags(const QModelIndex &index) const
{
    return QSortFilterProxyModel::flags(index) | Qt::ItemIsUserCheckable;
}

void SkillsProxyModel::setClassSkills(const QModelIndex &sourceIndex)
{
    m_classSkills = reinterpret_cast<Skills*>(sourceIndex.internalPointer());
}

